<template>
  <div>
    <div class="header">
      <van-nav-bar
        title="订单确认"
        left-text="返回"
        @click-left="onclickLeft"
        left-arrow
      >
      </van-nav-bar>
    </div>
    <!-- 服务地址按钮 -->
    <div class="address">
      <van-cell
        @click="showPopup"
        title="服务地址"
        icon="location-o"
        :value="content"
      >
        <!-- 订单倒计时 -->
        <van-count-down :time="time"
      /></van-cell>
      <!-- 返回的服务地址表格 -->
      <van-cell-group class="address_cell" v-model="addressData">
        <van-cell title="用户名" :value="content1"></van-cell>
        <van-cell title="电话" :value="content2"></van-cell>
        <van-cell title="地址" :value="content3"></van-cell>
      </van-cell-group>

      <!-- 服务地址按钮 -->
      <van-action-sheet v-model="show_adress" title="选择地址">
        <!-- 地址列表 -->
        <!-- chosenAddressId选中的地址id -->
        <!-- ：list地址数据数组 -->
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          add-button-text="确定"
          @select="swicthClick"
          @add="confirmaddress(chosenAddressId)"
        />
      </van-action-sheet>
    </div>
    <br /><br /><br /><br />
    <!-- 订单详情 -->
    <van-collapse v-model="activeNames">
      <van-collapse-item title="订单详情" class="row" icon="orders-o" name="1">
        <van-row v-for="order in orderLines.values()" :key="order.productId">
          <van-col span="10">{{ order.productName }}</van-col>
          <van-col span="8">￥{{ order.price }}元</van-col>
          <van-col span="2">x{{ order.number }}</van-col>
        </van-row>
        <!-- 总价 -->
        <van-row>
          <van-col span="" style="margin-left: 230px">
            总计:￥{{ total }}元</van-col
          >
        </van-row>
      </van-collapse-item>
    </van-collapse>
    <!-- 服务时间 -->
    <div>
      <van-cell
        title="服务时间"
        @click="showPopu_time"
        icon="clock-o"
        value="selectTime"
        size="large"
      >
        {{ selectTime }}</van-cell
      >
      <!-- 时间选择器 -->
      <van-popup
        v-model="show_time"
        position="bottom"
        :style="{ height: '50%' }"
      >
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="请选择年月日时分"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="confirm"
          @cancel="cancel"
          :formatter="formatter"
        />
      </van-popup>
    </div>
    <!-- 提交订单按钮 -->
    <div class="div_but">
      <van-cell
        title="确认提交"
        @click="comfirmSubmit"
        class="button_sub"
        @select="reCharge"
      />
      <van-action-sheet
        v-model="show_cencel"
        :actions="actions"
        cancel-text="取消"
        close-on-click-action
        @cancel="onCancel"
      />

      <!-- 充值弹窗 -->
      <van-popup
        v-model="show_recharge"
        position="bottom"
        :style="{ height: '40%' }"
      >
        <div class="rech">余额不足，请充值</div>
        <div>订单总价：￥{{ total }}</div>
        <van-cell-group>
          <van-field
            v-model="money"
            label="充值金额"
            placeholder="金额最高为1000"
          />
        </van-cell-group>
        <button @click="reCharge_con" class="reCharge_con1">确认充值</button>
      </van-popup>
      <!-- 充值成功提示 -->
      <van-notify v-model="show_succes" type="success" class="succes">
        <span>充值成功</span>
      </van-notify>
      <!-- 充值失败提示 -->
      <van-notify v-model="show_fail" type="success" class="succes">
        <span>充值失败</span>
      </van-notify>
      <!-- 下单成功提示 -->
      <van-notify v-model="show_sucess_order" type="success" class="succes">
        <span>下单成功</span>
      </van-notify>
      <!-- 下单失败提示 -->
      <van-notify v-model="show_fail_order" type="success" class="succes">
        <span>下单失败</span>
      </van-notify>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapState, mapMutations, mapActions } from "vuex";
import { get, post_json } from "@/http/axios";
export default {
  data() {
    return {
      // 充值
      money: "",
      customerId: "",
      activeNames: ["1"],
      actions: [{ name: "充值" }],
      //弹窗的显示与隐藏
      show_adress: false,
      show_time: false,
      show_cencel: false,
      show_recharge: false,
      show_succes: false,
      show_fail: false,
      show_order: false,
      show_fail_order: false,
      show_sucess_order:false,
      //服务日期
      minDate: new Date(),
      maxDate: new Date(2043, 0, 1),
      currentDate: new Date(),
      selectTime: new Date(),
      //地址
      content: "",
      content1: "",
      content2: "",
      content3: "",
      chosenAddressId: "2300",
      time: 30 * 60 * 60 * 1000,
      //接收地址数据
      addressData: [],
      orderLines1: [],
      addressId: "",
    };
  },

  mounted() {
    // 自定义日期的最小值
    var time1 = 2021;
    var time2 = 1;
    var time3 = 1;
    var time4 = 0;
    var time5 = 0;
    this.minDate = new Date(time1, time2, time3, time4, time5);
  },

  computed: {
    // 购物车总价
    ...mapGetters("shopcart", ["total"]),
    //获取购物车数据辅助函数
    ...mapState("shopcart", ["orderLines"]),
    //获取购物车数据辅助函数
    ...mapState("user", ["userInfo"]),
    //用户信息 登录token
    ...mapState("user", ["token"]),

    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressArr = this.addressData.list;
      let addressList = [];
      if (!addressArr) {
        return;
      }
      addressArr.forEach((item, index) => {
        let addressObj = {};
        (addressObj.id = item.id),
          (addressObj.name = item.username),
          (addressObj.tel = item.telephone),
          (addressObj.address =
            item.province + item.city + item.area + item.address),
          (addressObj.isDefault = item.isDefault);
        addressList.push(addressObj);
      });
      return addressList;
    },
  },

  methods: {
    // 引入购物车模块的方法
    ...mapMutations("shopcart", ["clearShopcart"]),
    // 引入获取产品栏目数据的方法
    ...mapActions("user", ["getUserInfo"]),
    //获取服务地址
    async getAddressData() {
      let data = {
        page: 1,
        pageSize: 1000,
      };
      let res = await get("/address/pageQuery", data);
      // 将拿到的数据赋值给轮播图数组
      this.addressData = res.data.data;
      return res;
    },
    // 点击确定返回选择的地址信息
    confirmaddress(chosenAddressId) {
      let addressData = {};
      for (let index = 0; index < this.addressList.length; index++) {
        addressData = this.addressList[index];

        if (chosenAddressId == addressData.id) {
          (this.content1 = addressData.name),
            (this.content2 = addressData.tel),
            (this.content3 = addressData.address);
        }
      }
      this.show_adress = false;
      let addressId1 = addressData.id;
      console.log(addressId1, "addressId");
    },
    //点击服务地址的显示与隐藏
    showPopup() {
      this.show_adress = true;
    },
    //点击服务地址按钮相应
    swicthClick(item, index) {
      console.log(index);
      console.log(item);
    },
    // 导航栏的返回按钮
    onclickLeft() {
      this.$router.go(-1);
      this.clearShopcart();
    },
    //日期选择器
    formatter(type, value) {
      if (type === "year") {
        this.value1 = value; // 可以拿到当前点击的数值
        return `${value}年`;
      } else if (type === "month") {
        this.value2 = value;
        return `${value}月`;
      } else if (type === "day") {
        this.value3 = value;
        return `${value}日`;
      } else if (type === "hour") {
        this.value4 = value;
        return `${value}时`;
      } else if (type === "minute") {
        this.value5 = value;
        return `${value}分`;
      }
    },
    showPopu_time() {
      this.show_time = true;
    },
    // 日期选择器
    confirm() {
      this.selectTime = `${this.value1}-${this.value2}-${this.value3} ${this.value4}:${this.value5}`;
      console.log(
        "用户选择的日期",
        new Date(this.currentDate).getTime(),
        this.selectTime
      );
      this.show_time = false;
    },
    // 日期选择器的取消按钮
    cancel() {
      this.show_time = false;
    },
    //确认订单按钮
    async comfirmSubmit() {
      let msg = localStorage.getItem("token");
      let res = await get("/user/info", { token: msg });
      this.customerId = res.data.data.id;
      let total = this.total;
      let balance = res.data.data.balance;
      console.log(balance);
      if (balance >= total) {
        let res2 = this.sendOrder();
        console.log(res2);
      } else {
        this.show_recharge = true;
      }
    },
    //取消按钮
    onCancel() {
      this.show_cencel = false;
    },
    //发送订单
    async sendOrder() {
      let customerId = this.customerId;
      let addressId = this.chosenAddressId;
      let selectTime = Date.parse(this.selectTime);
      var data = {
        addressId: addressId,
        customerId: customerId,
        orderLines: Array.from(this.orderLines.values()),
        serviceTime: selectTime,
      };
      console.log(data);
      let res1 = await post_json("/order/submitOrder", data);
      console.log(res1,"777777");
      
      if (res1.data.status==200) {
        this.show_sucess_order = true;
        setTimeout(() => {
          
          this.show_sucess_order = false;
          
        }, 600); 
        this.$router.push('/manager/order')
      }
    },
    //充值按钮
    reCharge() {
      this.show_recharge = true;
    },
    async reCharge_con() {
      let data = {
        money: this.money,
        customerId: this.customerId,
      };
      let res = await get("/account/recharge", data);
      let msg = localStorage.getItem("token");
      let res1 = await get("/user/info", { token: msg });
      this.balance1 = res1.data.data.balance;
      if (this.money<=1000) {
        //充值成功提示
        this.show_recharge = false;
        this.show_succes = true;
        setTimeout(() => {
          this.show_succes = false;
        }, 800);
      }else{
        //充值失败提示
        this.show_fail = true;
        setTimeout(() => {
          this.show_fail = false;
        }, 800);
      }
    },
  },

  created() {
    this.sendOrder();
    // 自动在表格中形成第一个默认地址
    this.getAddressData().then((res) => {
      (this.content1 = res.data.data.list[0].username),
        (this.content2 = res.data.data.list[0].telephone),
        (this.content3 =
          res.data.data.list[0].province +
          res.data.data.list[0].city +
          res.data.data.list[0].area +
          res.data.data.list[0].address);
    });
  },
};
</script>

<style scoped>
* {
  margin: auto;
}
.address {
  height: 105px;
}
.van-count-down {
  font-size: 18px;
  float: right;
}
.row {
  text-align: center;
  padding: 3px 0;
}
.van-icon-edit {
  display: none;
}
.button_sub {
  width: 120px;
  color: white;
  background-image: linear-gradient(90deg, #ed4264, #bf73ff);
  border-radius: 15px;
  font-size: 18px;
  border: #fff;
  line-height: 25px;
  text-align: center;
}
.div_but {
  text-align: center;
  margin-top: 50px;
}
.rech {
  color: rgb(204, 103, 103);
  margin: 15px;
  font-size: 18px;
}
.reCharge_con1 {
  width: 100px;
  height: 35px;
  font-size: 17px;
  background-image: linear-gradient(90deg, #ed4264, #bf73ff);
  border-radius: 8px;
  margin-top: 15px;
  color: rgb(253, 249, 253);
}
.succes {
  background-image: linear-gradient(90deg, #ed4264, #bf73ff);
}
</style>